<template>



  <!-- 面包屑 -->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>
      <a href="/">流程引擎</a>
    </el-breadcrumb-item>
    <el-breadcrumb-item>流程表单</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 搜索区域 -->
  <div style="border: solid 1px #ccc ; padding: 20px; margin: 12px; min-width: 300px;">
    {{ formInline }}
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="行业名称">
        <el-select v-model="formInline.Industry" style="wid" placeholder="请选择行业" @change="getCategorys" clearable>
          <el-option v-for="ins in industrys" :label="ins.industryName" :value="ins.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="表单分类">
        <el-select v-model="formInline.CategoryCode" placeholder="请选择分类" clearable>
          <el-option v-for="c in categorys" :label="c.formCategoryName" :value="c.formCategoryCode" />
        </el-select>
      </el-form-item>

      <el-form-item label="表单名称">
        <el-input v-model="formInline.FormName" placeholder="请输入表单名称" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search()">查询</el-button>
        <el-button type="primary" @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div style="border: solid 1px #ccc ; padding: 20px; margin: 12px;">
    <el-button type="success" @click="toAdd()">新增</el-button>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed type="index" label="序号" width="80" />
      <el-table-column prop="formCode" label="表单编号" width="110" />
      <el-table-column prop="formName" label="表单名称" width="250" />
      <el-table-column prop="categoryCode" label="分类编号" width="110" />
      <el-table-column prop="categoryName" label="分类名称" width="130" />
      <el-table-column prop="industryName" label="所属行业" width="120" />
      <el-table-column fixed="right" label="操作" min-width="350">
        <template #default="scope">
          <el-button type="danger" size="small" @click="del(scope.row)">
            删除
          </el-button>
          <el-button type="primary" size="small" @click="toFormUpdate(scope.row)">编辑</el-button>
          <el-button type="success" size="small" @click="openFormFieldDialog(scope.row)">添加表单明细</el-button>
          <el-button type="warning" size="small">查询表单明细</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>


  <!-- 添加流程表单对话框 -->
  <el-dialog v-model="addFormDialog" title="添加流程表单" width="500">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">


      <el-form-item label="表单分类">
        <el-select v-model="ruleForm.categoryId" placeholder="请选择分类" clearable>
          <el-option v-for="c in categorys" :label="c.formCategoryName" :value="c.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="表单名称" prop="formName">
        <el-input v-model="ruleForm.formName" />
      </el-form-item>


      <el-form-item label="表单描述" prop="formDes">
        <el-input v-model="ruleForm.formDes" style="width: 400px" :rows="5" type="textarea" placeholder="请输入表单描述" />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          添加
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 修改流程表单对话框 -->
  <el-dialog v-model="updateFormDialog" title="修改流程表单" width="500">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">


      <el-form-item label="表单分类">
        <el-select v-model="ruleForm.categoryId" placeholder="请选择分类" clearable>
          <el-option v-for="c in categorys" :label="c.formCategoryName" :value="c.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="表单名称" prop="formName">
        <el-input v-model="ruleForm.formName" />
      </el-form-item>


      <el-form-item label="表单描述" prop="formDes">
        <el-input v-model="ruleForm.formDes" style="width: 400px" :rows="5" type="textarea" placeholder="请输入表单描述" />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="updateForm(ruleFormRef)">
          修改
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>


  <!-- 添加表单明细(字段列表)的对话框 -->
  <el-dialog top="35vh"  v-model="formDetailModel.addFormFieldDialog" title="添加表单明细" width="1200">
    <el-button type="success" size="small" @click="newFormField()"> 新增一行 </el-button>
    <!-- {{ formDetailModel }} -->
    <el-table :data="formDetailModel.fieldsTable" style="width: 100%">
      <el-table-column fixed type="index" label="序号" width="80" />
      <el-table-column prop="fieldName" label="字段名称" width="140">
        <template #default="scope">
          <el-input v-model="scope.row.fieldName"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="fieldDes" label="字段描述" width="140">
        <template #default="scope">
          <el-input v-model="scope.row.fieldDes"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="fieldType" label="字段类型" width="180">
        <template #default="scope">
          <el-select v-model="scope.row.fieldType" placeholder="请选择">
            <el-option v-for="t in formDetailModel.fieldTypes" :value="t.key" :label="t.value"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="fieldComponent" label="组件类型" width="180">
        <template #default="scope">
          <el-select v-model="scope.row.fieldComponent" placeholder="请选择">
            <el-option v-for="t in formDetailModel.fieldComponents" :value="t.key" :label="t.value"></el-option>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="fieldValue" label="默认值" width="180">
        <template #default="scope">
          <el-input v-model="scope.row.fieldValue"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="fieldOptions" label="选项" width="70">
        <template #default="scope">
         <el-button size="small" @click="openFieldOption(scope.row)"> ... </el-button>   <!--配置选项 -->
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="100">
        <template #default="scope">
          <el-button type="danger" size="small" @click="removeFormField(scope.$index)"> 移除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="formDetailModel.addFormFieldDialog = false">取消</el-button>
        <el-button type="primary" @click="saveFormField()">
          保存表单明细
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 表单明细字段选项弹窗 -->
  <el-dialog v-model="formDetailModel.setFieldOptionDiglog" title="配置字段选项" width="500">
   <!-- {{ formDetailModel.fieldOptionTable }} -->
    <el-button type="success" size="small" @click="newFieldOption()"> 新增选项 </el-button>
   {{ formDetailModel.currentFieldRow }}
    <el-table :data="formDetailModel.fieldOptionTable" style="width: 100%">
      <el-table-column fixed type="index" label="序号" width="80" />
      <el-table-column prop="key" label="选项键" width="120" >
        <template #default="scope">
             <el-input v-model="scope.row.key"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="value" label="选项值" width="120"  >
        <template #default="scope">
             <el-input v-model="scope.row.value"></el-input>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="removeFileOption(scope.row.$index)">
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
        <template #footer>
      <div class="dialog-footer">
        <el-button @click="formDetailModel.setFieldOptionDiglog = false">取消</el-button>
        <el-button type="primary" @click="saveFieldOption()">
          保存字段选项
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import myAxios from '@/http/axiosHelper';
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
const formInline = reactive({
  Industry: null,
  CategoryCode: '',
  FormName: '',
})
//分页变量对象
const page = reactive({
  PageIndex: 1,
  PageSize: 3,
  totalCount: 0
})

const tableData = ref([])
const search = () => {
  myAxios.get('/PERead/ProcessEngine/GetFormPages', {
    params: {
      IndustryId: formInline.Industry,
      CategoryCode: formInline.CategoryCode,
      FormName: formInline.FormName
    }
  }).then(res => {
    tableData.value = res.data.pageDatas
    page.totalCount = res.data.totalCount

  });
}
//行业列表
const industrys = ref([{
  "id": 1,
  "industryName": "行政"
}])
const getIndustry = () => {
  myAxios.get('/PERead/ProcessEngine/GetIndustry').then(res => {
    industrys.value = res.data.data
  })
  formInline.Industry = null
}
//表单分类列表
const categorys = ref([{
  "id": 700061378039813,
  "formCategoryName": "邻里纠纷问题",
  "formCategoryCode": "T0001",
  "industryId": 3,
  "industryName": "教育"
}])
const getCategorys = () => {
  myAxios.get('/PERead/ProcessEngine/SearchFormCategory',
    { params: { IndustryId: formInline.Industry } }).then(res => {
      categorys.value = res.data.data
    })
  formInline.CategoryCode = ''
}



//查询表单重置方法
const reset = () => {
  formInline.Industry = null
  formInline.CategoryCode = ''
  formInline.FormName = ''
}

//添加新的流程表单对话框
const addFormDialog = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "formName": "",
  "formDes": "",
  "categoryId": null
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  formName: [
    { required: true, message: '请输入表单名称', trigger: 'blur' },
    { min: 2, max: 15, message: '表单名称长度应为2-15', trigger: 'blur' },
  ], formDes: [
    { required: true, message: '请输入表单描述', trigger: 'blur' },
    { min: 15, message: '表单描述长度应大于15个文字', trigger: 'blur' },
  ]
})

const toAdd = () => {
  addFormDialog.value = true;
  ruleForm.categoryId = null;
  ruleForm.formDes = ''
  ruleForm.formName = ''
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      myAxios.post('/PEWrite/ProcessEngine/CreateForm', ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);//消息提示
          addFormDialog.value = false;
          search();
          formEl.resetFields()//重置     
        } else {
          ElMessage.error(res.data.msg);//消息提示
        }
      })
    } else {
      console.log('操作错误!', fields)
    }
  })
}




//添加表单明细(字段列表)  总对象
const formDetailModel = reactive({
  formId: null,
  addFormFieldDialog: false, //添加表单明细弹窗是否打开
  fieldsTable: <any>[{
    "id": 700776992190469,
    "formId": 700410342383621,
    "fieldName": "discussType",
    "fieldDes": "纠纷类型",
    "fieldType": "1",
    "fieldComponent": 4,
    "fieldValue": "",
    "fieldOptions": "[{'key':'感情',value:'感情'},{'key':'金钱',value:'金钱'}]"
  }],
  setFieldOptionDiglog: false,//设置表单明细字段选项弹窗是否打开
  fieldOptionTable: <any>[],//表单字段的选项集合
  fieldTypes: [{//所有的类型枚举列表
    "key": "1",
    "value": "字符串"
  }],
  fieldComponents: [
    {//所有的类型枚举列表
      "key": "1",
      "value": "单行文本框"
    }
  ],
  currentFieldRow:<any>[]
})

//打开明细弹窗,并且加载当前行流程的所有字段
const openFormFieldDialog = (flowRow: any) => {
  formDetailModel.formId = flowRow.id,
    formDetailModel.addFormFieldDialog = true;
  myAxios.get('/PERead/ProcessEngine/GetFormFields', { params: { FormId: flowRow.id } }).then(res => {
    formDetailModel.fieldsTable = res.data.data
  })
}
const newFormField = () => {//新增一行
  formDetailModel.fieldsTable.push({
    "id": 0,
    "formId": formDetailModel.formId,
    "fieldName": "",
    "fieldDes": "",
    "fieldType": null,
    "fieldComponent": null,
    "fieldValue": "",
    "fieldOptions": "[]"
  });
}

const removeFormField = (index: any) => {//移除
  formDetailModel.fieldsTable.splice(index, 1);
}
const saveFormField = () => {//调用后端批量保存流程表单明细(自定义的流程动态字段)接口
  myAxios.post('/PEWrite/ProcessEngine/SaveFormField', { formId: formDetailModel.formId, createFormFieldDTOs: formDetailModel.fieldsTable }).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg)
      formDetailModel.addFormFieldDialog = false;
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

//打开指定字段行的选项弹窗
const openFieldOption = (fieldRow:any) => {
  formDetailModel.setFieldOptionDiglog = true
  formDetailModel.fieldOptionTable = JSON.parse(fieldRow.fieldOptions) 
  formDetailModel.currentFieldRow = fieldRow
}

const newFieldOption = () => {
    formDetailModel.fieldOptionTable.push({key:'',value:''}) 
}

const saveFieldOption=()=>{
  formDetailModel.currentFieldRow.fieldOptions = JSON.stringify(formDetailModel.fieldOptionTable)
  formDetailModel.setFieldOptionDiglog=false
}

const removeFileOption=(index:any)=>{
   formDetailModel.fieldOptionTable.splice(index,1)
}

const getFieldTypes = () => {
  myAxios.get('/PERead/ProcessEngine/GetFieldTypes').then(res => {
    formDetailModel.fieldTypes = res.data.data
  })
}
const getComponents = () => {//查询所有组件列表,并赋值给  formDetailModel.fieldComponents
  myAxios.get('/PERead/ProcessEngine/GetComponents').then(res => {
    formDetailModel.fieldComponents = res.data.data
  })
}


const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


//删除流程表单
const del = (row: any) => {
  ElMessageBox.confirm(
    '您确认删除该流程吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      myAxios.put('/PEWrite/ProcessEngine/DelForm', row).then(res => {
        ElMessage.success(res.data.msg);//消息提示
        search();
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


//修改流程表单
const updateFormDialog = ref(false)

const toFormUpdate = (row: any) => {
  Object.assign(ruleForm, row)  //反填
  updateFormDialog.value = true;

}
const updateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      myAxios.put('/PEWrite/ProcessEngine/UpdateForm', ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);//消息提示
          updateFormDialog.value = false;
          search();
          formEl.resetFields()//重置     
        } else {
          ElMessage.error(res.data.msg);//消息提示
        }
      })
    } else {
      console.log('操作错误!', fields)
    }
  })
}


onMounted(() => {
  search()
  getIndustry()
  getCategorys()
  getFieldTypes()
  getComponents()
})
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>